//
//  CZPhotoView.swift
//  sinaSwifWeiBo
//
//  Created by 张雪雪 on 16/3/17.
//  Copyright © 2016年 张雪雪. All rights reserved.
//

import UIKit

let CZPhotoViewMargin: CGFloat = 10
let CZPhotoItmeMargin: CGFloat = 5
let  CZPhotoViewReuseIdentifier = "CZPhotoViewReuseIdentifier"

protocol CZPhotoCollectionViewCellDelegate:NSObjectProtocol{

    //删除指定的图片
    func didRemoveIndexImage(index:Int)

}

class CZPhotoView: UICollectionView ,UICollectionViewDataSource,CZPhotoCollectionViewCellDelegate,UICollectionViewDelegate{

    //闭包属性
    var closure:(() -> ())?
    
    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    //定义一个数组来存放图片
     var images : [UIImage] = [UIImage]()
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
    
        
        
        
    setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
    
    backgroundColor = UIColor.greenColor()
       //设置数据源代理
    dataSource = self
        
        delegate = self
        
        
      //注册cell
        registerClass(CZPhotoCollectionViewCell.self, forCellWithReuseIdentifier: CZPhotoViewReuseIdentifier)
       
        let ItemWH = (kUIScreenWidth - 2*CZPhotoViewMargin - 2*CZPhotoItmeMargin)/3
        flowLayout.itemSize = CGSizeMake(ItemWH, ItemWH)
        flowLayout.minimumInteritemSpacing = CZPhotoItmeMargin
        flowLayout.minimumLineSpacing = CZPhotoItmeMargin
        
    }
    
    //MARK:--添加图片对外公开一个方法
    func addImages(image:UIImage){
        
        images.append(image)
        //刷新数据
        reloadData()
    }
    
    deinit{
    
     print("88")
    
    }
  //MARK:--懒加载
    
    
}




//MARK:实现数据源方法

extension CZPhotoView{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if images.count == 0 || images.count == 9{
        //不显示加号
            return images.count
        
        }else{
        
            return images.count + 1
        
        }
    
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZPhotoViewReuseIdentifier, forIndexPath: indexPath) as! CZPhotoCollectionViewCell
    //数组越界就得判断
        if indexPath.item >= images.count{
        
        //越界 赋值
            cell.iconImage = nil
        
        
        }else{
        
        
            cell.iconImage = images[indexPath.item]
        
        }
        
        //正向传递用 属性
        cell.indexPath = indexPath
        
        cell.delegate = self
        
        cell.backgroundColor = randomColor()
        
        return cell
    }
    
    //实现代理方法
    func didRemoveIndexImage(index: Int) {
        //伤处指定的图片
        images.removeAtIndex(index)
        
        //刷新数据
        reloadData()
    }
    //MARK:-- 必须
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //必须是最后一个item 点击的时候调用
        if indexPath.item == images.count{
        
        //需要控制器区调用一下自己的方法
        print("加号按钮")
        
            closure?()
            
        }
        
        
    }
}

//自定义cell 
class CZPhotoCollectionViewCell:UICollectionViewCell{

    weak var delegate:CZPhotoCollectionViewCellDelegate?
    
    //定义一个属性
    var indexPath:NSIndexPath?
    
    //定义一个模型
    var iconImage: UIImage? {
    
        didSet{
        
            if iconImage == nil {
            
            //显示加号
                iconImageView.image = UIImage(named: "compose_pic_add")
            deleteButton.hidden = true
            }else{
            
                iconImageView.image = iconImage
            
                deleteButton.hidden = false
            }
        
        }
    
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){
    
    contentView.addSubview(iconImageView)
        contentView.addSubview(deleteButton)
        //设置约束 设置图片的约束
        iconImageView.frame = bounds
        //设置删除按钮的约束
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
    
    }

    
    @objc private func click(){
      print("删除选中图片")
    
        if let index = indexPath?.item{
            
            delegate?.didRemoveIndexImage(index)
        }
        
    }
    
    private lazy var iconImageView:UIImageView = UIImageView()

    //添加删除按钮
    private lazy var deleteButton : UIButton = {
    
    let button = UIButton(type: UIButtonType.Custom)
    //设置背景图片
        button.setImage(UIImage(named:"compose_photo_close"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_card_delete_highlighted"), forState: UIControlState.Highlighted)
        //设置大小
        button.sizeToFit()
        
        //添加点击事件
        button.addTarget(self, action: "click", forControlEvents: UIControlEvents.TouchUpInside)
    
    return button
    }()
    

}




